<template>
  <div class="login-page">
    <el-card>
      <template #header>黑马面经运营后台</template>
      <el-form ref="loginForm" autocomplete="off" :model="form" :rules="rules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="输入用户密码"></el-input>
        </el-form-item>

        <el-form-item class="tc">
          <el-button type="primary" @click="login">登 录</el-button>
          <el-button @click="reset">重 置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 调用form组件方法
// 1. 给form组件加上ref
// 2. 通过$refs获取组件实例
// 3. 调用具体方法
export default {
  name: 'login-page',
  data () {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          // required 必传  message: 报错信息
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { min: 5, max: 11, message: '请输入长度为5-11', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
          { pattern: /^\w{5,11}$/, message: '请输入5-11位的密码', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    async login () {
      console.log(this.$refs.loginForm)
      try {
        // 用validate方法校验输入内容是否通过
        await this.$refs.loginForm.validate()
        console.log('可以调用接口了')
        // 调用action(异步) async函数的调用会返回一个promise
        await this.$store.dispatch('user/loginAsync', { username: this.form.username, password: this.form.password })
        this.$message.success('登录成功')
        this.$router.push('/')
      } catch (error) {
        console.log(error)
      }
    },
    reset () {
      this.$refs.loginForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: url(@/assets/login-bg.svg) no-repeat center / cover;
  display: flex;
  align-items: center;
  justify-content: space-around;
  .el-card {
    width: 420px;
    ::v-deep .el-card__header{
      height: 80px;
      background: rgba(114,124,245,1);
      text-align: center;
      line-height: 40px;
      color: #fff;
      font-size: 18px;
    }
  }
  .el-form {
    padding: 0 20px;
  }
  .tc {
    text-align: center;
  }
}
</style>
